package com.fjrz.bbxwj.popup

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.*
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.entity.CommentChild
import com.fjrz.bbxwj.entity.CommentGroup
import com.fjrz.bbxwj.entity.CommentGroupResponse
import com.fjrz.bbxwj.main.video.adapter.DiscussGroupAdapter
import kotlinx.android.synthetic.main.popup_video_discuss.view.*
import razerdp.basepopup.BasePopupWindow


class VideoDiscussPopup(
    context: Context,
    val onDiscuss: (view: View, position: Int, commentGroup: CommentGroup) -> Unit,
    val onDiscussSend: (content: Content) -> Unit,
    val onLoadMore: (videoId: Int) -> Unit
) : BasePopupWindow(context) {

    class Content {
        var video_id: String? = null
        var content: String? = null
        var at_comment_id: String? = null
        var base_comment_id: String? = null
    }

    private var mContent: Content = Content()

    private var mVideoId: Int = 0

    init {

        setAdjustInputMethod(false)
        height = ScreenUtils.getAppScreenHeight() / 4 * 3
        popupGravity = Gravity.BOTTOM
        setAutoShowInputMethod(false)
        setOverlayNavigationBar(false)
        setBackgroundColor(0)
        setAlignBackground(true)
        setBlurBackgroundEnable(true)

    }

    private val discussGroupAdapter = DiscussGroupAdapter()

    override fun onCreateContentView(): View {
        return createPopupById(R.layout.popup_video_discuss)
    }

    override fun onViewCreated(contentView: View) {
        super.onViewCreated(contentView)
        contentView.findViewById<ImageView>(R.id.ivVideoDiscussClose).setOnClickListener {
            dismiss()
        }
        contentView.mSmartRefreshLayout.setOnLoadMoreListener {
            onLoadMore(mVideoId)
        }
        contentView.ivVideoDiscussSend.setOnClickListener {
            if (mContent.content.isNullOrEmpty()) {
                ToastUtils.showShort("请输入内容")
            } else {
                onDiscussSend(mContent)
                contentView.etVideoDiscussContent.text.clear()
            }
        }
        contentView.etVideoDiscussContent.addTextChangedListener {
            mContent.content = if (it.isNullOrEmpty()) null else it.toString()
        }

        setOnKeyboardChangeListener { keyboardBounds, isVisible ->
            //keyboardBounds.
            if (isVisible) {
                contentView.llVideoDiscussBottom.apply {
                    setBackgroundColor(ColorUtils.getColor(R.color.FF_212121))
                    setPadding(
                        0,
                        ConvertUtils.dp2px(10f),
                        0,
                        keyboardBounds.height() + ConvertUtils.dp2px(10f)
                    )
                }
                contentView.etVideoDiscussContent.maxLines = 3
            } else {
                contentView.llVideoDiscussBottom.apply {
                    setBackgroundColor(0)
                    setPadding(
                        0,
                        ConvertUtils.dp2px(10f),
                        0,
                        ConvertUtils.dp2px(10f)
                    )
                }
                contentView.etVideoDiscussContent.maxLines = 1
            }
        }
    }

    override fun onCreateShowAnimation(width: Int, height: Int): Animation {
        return TranslateAnimation(
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 1f,
            Animation.RELATIVE_TO_PARENT, 0f
        ).apply { duration = 300L }
    }

    override fun onCreateDismissAnimation(): Animation {
        return TranslateAnimation(
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 0f,
            Animation.RELATIVE_TO_PARENT, 1f
        ).apply { duration = 300L }
    }

    fun initDiscussView(videoId: Int): VideoDiscussPopup {
        mVideoId = videoId
        mContent = Content()
        mContent.video_id = mVideoId.toString()
        contentView.etVideoDiscussContent.text.clear()
        contentView.etVideoDiscussContent.hint = "说点什么吧~"
        contentView.mSmartRefreshLayout.setEnableRefresh(false)
        contentView.findViewById<RecyclerView>(R.id.rvVideoDiscussBody).apply {
            itemAnimator?.changeDuration = 0
        }.adapter =
            discussGroupAdapter.apply {
                setEmptyView(createViewEmptyLoad())
            }
        discussGroupAdapter.setOnItemChildClickListener { adapter, view, position ->
            val commentGroup: CommentGroup = discussGroupAdapter.getItem(position)
            if (view.id == R.id.clDiscussGroup) {
                mContent.at_comment_id = null
                mContent.base_comment_id = commentGroup.id.toString()
                contentView.etVideoDiscussContent.apply {
                    text.clear()
                    hint = "回复:${commentGroup.user.nickname}"
                    KeyboardUtils.showSoftInput(this)
                }
            } else {
                onDiscuss(view, position, commentGroup)
            }
        }
        discussGroupAdapter.setOnItemClickCommentChildListener(object :
            DiscussGroupAdapter.OnItemClickCommentChildListener {
            override fun onItemClick(view: View, position: Int, commentChild: CommentChild) {
                mContent.at_comment_id = commentChild.id.toString()
                mContent.base_comment_id = null
                contentView.etVideoDiscussContent.apply {
                    text.clear()
                    hint = "回复:${commentChild.user.nickname}"
                    KeyboardUtils.showSoftInput(this)
                }
            }
        })
        return this
    }

    fun setDiscussData(response: CommentGroupResponse) {

        contentView.mSmartRefreshLayout.finishLoadMore()


        val isLoadMore: Boolean = response.loadMore
        LogUtils.e("==isLoadMore====${isLoadMore}")
        val commentGroups: MutableList<CommentGroup> = response.data.data
        if (commentGroups.isNullOrEmpty()) {
            discussGroupAdapter.setEmptyView(createViewEmptyNull(hint = "暂无数据,来抢沙发~"))
        }
        if (isLoadMore) {
            discussGroupAdapter.addData(commentGroups)
        } else {
            discussGroupAdapter.setNewInstance(commentGroups)
        }
        if (commentGroups.size < 10) {
            discussGroupAdapter.setFooterView(createViewFooter())
            contentView.mSmartRefreshLayout.setEnableLoadMore(false)
        } else {
            discussGroupAdapter.removeAllFooterView()
            contentView.mSmartRefreshLayout.setEnableLoadMore(true)
        }
//        discussGroupAdapter.setNewInstance(commentGroups)
    }

    fun updateDiscussMore(position: Int, commentChild: MutableList<CommentChild>) {
        discussGroupAdapter.setData(position, discussGroupAdapter.getItem(position).apply {
            setCommentChildItem(commentChild)
        })
    }

    fun updateDiscussGreat(position: Int, like: Int) {
        discussGroupAdapter.setData(position, discussGroupAdapter.getItem(position).apply {
            this.like = like
            this.likes = if (like == 1) likes + 1 else likes - 1
        })
    }

    fun resetDiscussView() {
        mContent = Content()
        mContent.video_id = mVideoId.toString()
        contentView.etVideoDiscussContent.text.clear()
        contentView.etVideoDiscussContent.hint = "说点什么吧~"
        KeyboardUtils.hideSoftInput(contentView.etVideoDiscussContent)
    }

    fun createViewEmptyNull(hint: String): View {
        return context.layoutInflater.inflate(com.module.lemlin.R.layout.view_empty_null, null)
            .apply {
                findViewById<ImageView>(com.module.lemlin.R.id.ivEmptyNullImage).visibility =
                    View.GONE
                findViewById<TextView>(com.module.lemlin.R.id.tvEmptyNullHint).text = hint
            }
    }

    fun createViewEmptyLoad(): View {
        return context.layoutInflater.inflate(com.module.lemlin.R.layout.view_empty_load, null)
    }

    fun createViewFooter(hint: String = "没有更多数据"): View =
        TextView(context).apply {
            layoutParams = FrameLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                ConvertUtils.dp2px(30f)
            )
            gravity = Gravity.CENTER
            textSize = 13f
            text = hint
            setTypeface(null, Typeface.BOLD)
            setTextColor(Color.parseColor("#CCCCCC"))
        }
}